<?php
/**
 * Created by PhpStorm.
 * User: liyiming
 * Date: 2020/7/20
 * Time: 16:58
 */
interface ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod);
}


class Express_SF implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $sfe = new SFExpressClass($debug,$data['company']['sf_dev_key'],$data['company']['sf_dev_id'],$data['company']['sf_user_name']);
        $info = $sfe->send_parameter($data);
        if(is_array($info)){
            $info = array_merge($info, $sendorder_result);
        }

        $log->lwrite($data['shop_express_no'].'=>sf推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));
        if($info && $info['error_code'] == 0){   //推送成功
            # 推送小费
            $where = array('AND'=>array('='=>array('order_no' => $info['result']['shop_order_id'],"isdeleted" => 0, "status" => 1)));
            $tip_res = $mod->getItemByOther($where,'tip_list');

            $log->lwrite('查找小费信息=>' . json_encode($tip_res,JSON_UNESCAPED_UNICODE));
            if($tip_res && count((array)$tip_res) > 0){
                $tips = 0;
                $tipIDs = [];
                foreach($tip_res as $k=>$t){
                    $tips += $t['price'];
                    $tipIDs[$k]['id'] = $t['id'];
                }
                $addFee = $sfe->AddOrderGratuityFee($info['result']['shop_order_id'],$data['shop_no'],$tips);
                $log->lwrite('顺丰小费=>' . json_encode($addFee,JSON_UNESCAPED_UNICODE));

                if($addFee && $addFee['error_code'] == 0){
                    $tip['push_state'] = 1;
                }else{
                    $tip['push_state'] = 9;
                }
                $tip['push_time'] = 'now()';
                $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
                foreach ($tipIDs as $v){
                    $where_fields = array("AND" => array("=" => array('id' => $v['id'], "isdeleted" => 0)));
                    $mod->updateItem($tip, $where_fields, 'tip_list');
                }
            }




            $_result=[];
            $_result['shop_express_no'] = $info['result']['shop_order_id'];
            $_result['express_order_no'] = $info['result']['sf_order_id'];
            $_result['express_fee'] = $info['result']['total_price']/100;

            //for express_data
            $info['result_code'] = 0;
            $info['express_code'] = $info['error_code'];
            $info['express_code_desc'] = '创建成功';//$info['error_msg'];
            return $result = ['status'=>'200','result'=>$_result,'info'=>$info];

        }else {  //推送失败
            $_result = [];
            $_result['shop_express_no'] = $data['shop_express_no'];

            //for express_data
            $info['express_code_desc'] = $info['error_data']['desc'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
    }
}


class Express_DD implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $dde = new DDExpressClass($debug,$data['dd_source_id'],$data['dd_app_key'],$data['dd_app_secret']);
        $info = $dde->send_parameter($data);
        $log->lwrite($data['shop_express_no'].'=>DD推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));

        if($info && $info['status'] == 'success'){   //推送成功
            $_result = [];
            $_result['shop_express_no'] = $data['shop_express_no'];        # 达达不返 快点单号 和门店订单号
            $_result['express_order_no'] = $data['shop_express_no'];
            $_result['express_fee'] = $info['result']['deliverFee'];

            //for express_data
            $info['result_code'] = 0;
            $info['express_code'] = $info['code'];
            $info['express_code_desc'] = $info['msg'];
            return $result = ['status'=>'200','result'=>$_result,'info'=>$info];

        }else {  //推送失败
            if($info == false){
                //for express_data
                $info['express_code_desc'] = '达达请求返回：false';
            }else{
                //for express_data
                $info['express_code_desc'] = $info['msg'];
            }
            $info=array_merge($info,$sendorder_result);

            $_result = [];
            $_result['shop_express_no'] = $data['shop_express_no'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }


    }
}


class Express_SS implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $sse = new SSExpressClass($debug,$data['ss_clientId'],$data['ss_clientSecret'],$data['ss_shopId']);
//        $ShopList = $sse->get_shop_list();
        $info_jj = $sse->billing($data);
        $log->lwrite($data['shop_express_no'].'=>SS计价结果:'.json_encode($info_jj, JSON_UNESCAPED_UNICODE));

        # 推送计价成功 发送订单
        if($info_jj && $info_jj['status'] == 200){
            $parameter['issOrderNo'] = $info_jj['data'][0]['issOrderNo'];                                      # 闪送订单号
            $order_info = $sse ->send_parameter($parameter);
            $log->lwrite($data['shop_express_no'].'=>SS推送结果:'.json_encode($order_info, JSON_UNESCAPED_UNICODE));

            $info = array_merge($order_info,$sendorder_result);
            if($order_info && $order_info['status'] == 200){
                $_result=[];
                $_result['shop_express_no'] = $order_info['data'][0]['orderNoList'][0]['orderNo'];          # 派单单号
                $_result['express_order_no'] = $order_info['data'][0]['issOrderNo'];                        # 快递订单单号
                $_result['express_fee'] = $order_info['data'][0]['totalFee']/100;      # 费用

                //for express_data
                $info['result_code'] = 0;
                $info['express_code'] = $order_info['status'];
                $info['express_code_desc'] = '下单成功';
                return $result = ['status'=>'200','result'=>$_result,'info'=>$info];

            }else{
                $_result = [];
                $_result['shop_express_no'] = $data['shop_express_no'];

                //for express_data
                $info['express_code_desc'] = $order_info['msg'];
                $info['result_code'] = 1;
                $info['express_code'] = $order_info['status'];
                return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
            }


        }else {  //推送失败
            $_result = [];
            $info = array_merge($info_jj,$sendorder_result);
            $_result['shop_express_no'] = $data['shop_express_no'];

            //for express_data
            $info['express_code_desc'] = $info_jj['msg'];
            $info['result_code'] = 1;
            $info['express_code'] = $info_jj['status'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }

    }
}

class Express_JRD implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $JRD = new JRDExpressClass($debug,$data['jrd_sign']);
        $info = $JRD->push_order($data);
        $log->lwrite($data['shop_express_no'].'=>jrd推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));
        $info = array_merge($info,$sendorder_result);

        if($info && $info['error_code'] == 0){   //推送成功
            # 推送小费
            $where = array('AND'=>array('='=>array('order_no' => $info['result']['partner_order_no'],"isdeleted" => 0, "status" => 1)));
            $tip_res = $mod->getItemByOther($where,'tip_list');

            $log->lwrite('查找小费信息=>' . json_encode($tip_res,JSON_UNESCAPED_UNICODE));
            if($tip_res && count((array)$tip_res) > 0){
                # 查找门店编号
                $where_store = array('AND'=>array('='=>array('shop_express_no' => $info['result']['partner_order_no'], "isdeleted" => 0, "status" => 1)));
                $store_no = $mod->getItemByOther($where_store,'orders_express');
                $log->lwrite('查找门店编号=>' . json_encode($store_no,JSON_UNESCAPED_UNICODE));

                $where_store = array('AND'=>array('='=>array('store_id' => $store_no[0]['shop_no'], "isdeleted" => 0, "zp_status" => 1)));
                $store_res = $mod->getItemByOther($where_store,'xd_store');
                $log->lwrite('查找门店快点参数=>' . json_encode($store_res,JSON_UNESCAPED_UNICODE));

                $tips = 0;
                $tipIDs = [];
                foreach($tip_res as $k=>$t){
                    $tips += $t['price'];
                    $tipIDs[$k]['id'] = $t['id'];
                }

                $addFee = $JRD->addTip($info['result']['order_no'],$tips);
                $log->lwrite('今日达小费=>' . json_encode($addFee,JSON_UNESCAPED_UNICODE));

                if($addFee && $addFee['error_code'] == 0){
                    $tip['push_state'] = 1;
                }else{
                    $tip['push_state'] = 9;
                }
                $tip['push_time'] = 'now()';
                $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
                foreach ($tipIDs as $v){
                    $where_fields = array("AND" => array("=" => array('id' => $v['id'], "isdeleted" => 0)));
                    $mod->updateItem($tip, $where_fields, 'tip_list');
                }
            }


            $_result=[];
            $_result['shop_express_no'] = $info['result']['partner_order_no'];   # 宅配传过去
            $_result['express_order_no'] = $info['result']['order_no']; # 第三方快递号
            $_result['express_fee'] = $info['result']['total_price'];

            //for express_data
            $info['result_code'] = 0;
            $info['express_code'] = 0;
            $info['express_code_desc'] = $info['error_msg'];
            return $result = ['status'=>'200','result'=>$_result,'info'=>$info];

        }else {  //推送失败
            $_result = [];
            $_result['shop_express_no'] = $data['shop_express_no'];
            //for express_data
            $info['express_code_desc'] = $info['error_msg'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];

        }
    }
}


class Express_UU implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $uue = new UUExpressClass($debug,$data['uu_app_id'],$data['uu_app_key'],$data['uu_open_id']);
        $tolat = isset($data['slat']) ? $data['slat'] :$data['lat'];
        $tolng = isset($data['slng']) ? $data['slng'] :$data['lng'];
        $parameter = [
            'deliver_lng' => $data['shop_longitude'],                                                   # 起始地坐标经度
            'deliver_lat' => $data['shop_latitude'],                                                    # 起始地坐标纬度
            'to_lng' => $tolng,                                                                         # 收货地坐标经度
            'to_lat' => $tolat,                                                                         # 收货地坐标纬度
            'city_name' => $data['deliver_city'],                                                       # 订单所在城市名 称(如郑州市就填”郑州市“，必须带上“市”)
            'receiver_address' => $data['receiver_address'],                                            # 目的地
            'shop_express_no' => $data['shop_express_no'],                                              # 第三方对接平台订单id
            'deliver_province' => $data['deliver_province'],                                            # 起始地址
            'deliver_city' => $data['deliver_city'],                                                    # 起始地址
            'deliver_area' => $data['deliver_area'],                                                    # 起始地址
            'deliver_address' => $data['deliver_address'],                                              # 起始地址
        ];
        $result = $uue->getorderprice($parameter);
        $info = array_merge($result,$sendorder_result);

        if($result['price_token'] && strtolower($result['return_code']) == 'ok'){
            $data['price_token'] = $result['price_token'];
            $data['total_money'] = $result['total_money'];
            $data['balance_paymoney'] = $result['need_paymoney'];
            $addorder = $uue->addorder($data);
            if(strtolower($addorder['return_code']) == 'ok'){

                # 推送小费
                $where = array('AND'=>array('='=>array('order_no' => $data['shop_express_no'],"isdeleted" => 0, "status" => 1)));
                $tip_res = $mod->getItemByOther($where,'tip_list');
                $log->lwrite('查找小费信息=>' . json_encode($tip_res,JSON_UNESCAPED_UNICODE));
                if($tip_res && count((array)$tip_res) > 0){
                    $where_store = array('AND'=>array('='=>array('store_id' => $data['shop_no'], "isdeleted" => 0, "zp_status" => 1)));
                    $store_res = $mod->getItemByOther($where_store,'xd_store');
                    $log->lwrite('查找门店快点参数=>' . json_encode($store_res,JSON_UNESCAPED_UNICODE));

                    $tips = 0;
                    $tipIDs = [];
                    foreach($tip_res as $k=>$t){
                        $tips += $t['price'];
                        $tipIDs[$k]['id'] = $t['id'];
                    }
                  $tipData = [
                      'order_code' => $addorder['ordercode'],
                      'origin_id' => $addorder['origin_id'],
                      'onlinefee' => $tips,
                  ];
                    $addFee = $uue->payonlinefee($tipData);
                    $log->lwrite('今日达小费=>' . json_encode($addFee,JSON_UNESCAPED_UNICODE));

                    if($addFee && $addFee['return_code'] == 'ok'){
                        $tip['push_state'] = 1;
                    }else{
                        $tip['push_state'] = 9;
                    }
                    $tip['push_time'] = 'now()';
                    $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
                    foreach ($tipIDs as $v){
                        $where_fields = array("AND" => array("=" => array('id' => $v['id'], "isdeleted" => 0)));
                        $mod->updateItem($tip, $where_fields, 'tip_list');
                    }
                }

                $_result = [];
                $_result['shop_express_no'] = $addorder['origin_id'];
                $_result['express_order_no'] = $addorder['ordercode'];
                $_result['express_fee'] = $result['need_paymoney'];     # 优惠后  实际支付金额

                //for express_data
                $info['result_code'] = 0;
                $info['express_code'] = $info['return_code'];
                $info['express_code_desc'] = $info['return_msg'];
                return $result = ['status'=>'200','result'=>$_result,'info'=>$info];
            }else{
                $_result = [];
                $_result['shop_express_no'] = $data['shop_express_no'];

                //for express_data
                $info['express_code_desc'] = $addorder['return_msg'];
                return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
            }
        }else{
            $_result = [];
            $_result['shop_express_no'] = $data['shop_express_no'];

            //for express_data
            $info['express_code_desc'] = $result['return_msg'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
    }
}



class Express_SLW implements ExpressTactics{
    public function PushOrder($debug,$data,$log,$sendorder_result,$mod){
        $SLW = new SLWExpressClass($debug,$data['user365Id']);
        $r = new SLWTokenClass($debug,$mod);
        $token = $r->token();
        $_result = [];
        if(empty($token)){
            $_result['shop_express_no'] = $data['shop_express_no'];
            //for express_data
            $info['express_code_desc'] = 'token为空';
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
        $data['token'] = $token;
        $expressCost = $SLW->expressCost($data);
        $log->lwrite($data['shop_express_no'].'=>365推送DATA:'.json_encode($data, JSON_UNESCAPED_UNICODE));
        $log->lwrite($data['shop_express_no'].'=>365推送结果:'.json_encode($expressCost, JSON_UNESCAPED_UNICODE));
        if(empty($expressCost)){
            $_result['shop_express_no'] = $data['shop_express_no'];
            //for express_data
            $info['express_code_desc'] = '推送结果为空';
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
        if($expressCost['errorcode'] > 0){
            $_result['shop_express_no'] = $data['shop_express_no'];
            $info['express_code_desc'] = !empty($expressCost['message']) ? $expressCost['message'] : '推送结果为空';
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
        $info = array_merge($expressCost,$sendorder_result);

        if($expressCost['data']['totalCost'] && $expressCost['errorcode'] == 0){    # 计价成功
            $data['totalCost'] = $expressCost['data']['totalCost'];
            $createOrder = $SLW->createOrder($data);
            $info = array_merge($createOrder,$sendorder_result);

            if($createOrder['errorcode'] == 0 && $createOrder['data']){
                $_result['shop_express_no'] = $data['shop_express_no'];     # 宅配传过去
                $_result['express_order_no'] = $createOrder['data'];               # 第三方快递号
                $_result['express_fee'] = $data['totalCost'];

                //for express_data
                $info['result_code'] = 0;
                $info['express_code'] = 0;
                $info['express_code_desc'] = $createOrder['message'];
                return $result = ['status'=>'200','result'=>$_result,'info'=>$info];
            }else{
                $_result['shop_express_no'] = $data['shop_express_no'];
                //for express_data
                $info['express_code_desc'] = $createOrder['message'];
                return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
            }

        }else {  //推送失败
            $_result['shop_express_no'] = $data['shop_express_no'];
            //for express_data
            $info['express_code_desc'] = $expressCost['message'];
            return $result = ['status'=>'400','result'=>$_result,'info'=>$info];
        }
    }
}


class GetExpressTactics{
    protected $express_class = null;
    public function get_result($debug,$data,$log,$sendorder_result,$mod){
        $this->express_class = 'Express_' . strtoupper($data['express_type']);
        $cls = new $this->express_class;
        return $cls->PushOrder($debug,$data,$log,$sendorder_result,$mod);
    }
}

